package com.nbsaas.boot.pay.ext.resource;

import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.nbsaas.boot.pay.api.apis.PaymentApi;
import com.nbsaas.boot.pay.api.domain.field.PaymentField;
import com.nbsaas.boot.pay.api.domain.request.PaymentRequest;
import com.nbsaas.boot.pay.api.domain.response.PaymentResponse;
import com.nbsaas.boot.pay.ext.apis.PayHandler;
import com.nbsaas.boot.pay.ext.apis.PaymentHandleApi;
import com.nbsaas.boot.pay.ext.domain.enums.PayState;
import com.nbsaas.boot.rest.filter.Filter;
import com.nbsaas.boot.rest.response.ResponseObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service
public class PaymentHandleResource implements PaymentHandleApi {

    @Resource
    private PaymentApi paymentApi;


    @Resource
    private Map<String, PayHandler> payHandleMap = new HashMap<>();

    @Transactional
    @Override
    public ResponseObject<PaymentResponse> handle(WxPayOrderNotifyResult notifyResult) {
        ResponseObject<PaymentResponse> result= new ResponseObject<>();

        PaymentResponse payment = paymentApi.oneData(Filter.eq(PaymentField.payNo, notifyResult.getOutTradeNo()));
        if (payment != null) {
            if (payment.getPayState() == PayState.wait) {
                PaymentRequest request=new PaymentRequest();
                request.setId(payment.getId());
                request.setPayState(PayState.success);
                request.setBussNo(notifyResult.getTransactionId());
                request.setPaymentDate(new Date());
                paymentApi.update(request);
                if (payment.getHandle() != null) {
                    PayHandler payHandle = payHandleMap.get(payment.getHandle());
                    if (payHandle != null) {
                        try {
                            System.out.println(":" + payHandle.getClass().getSimpleName());
                            payment.setBussNo(notifyResult.getTransactionId());
                            payHandle.pay(payment);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        System.out.println("无效支付处理器");
                    }
                }
            }
        }else{
            System.out.println("无效支付单"+notifyResult.getOutTradeNo());
        }
        return result;
    }
}
